import request from '@/framework-core/axios';
import website from '@/framework-core/config/website';
//防抖
import { debounce} from '@/framework-core/utils/util'

import _ from 'lodash';
export const check = [
  'year',
  'month',
  'week',
  'date',
  'time',
  'datetime',
  'daterange',
  'timerange',
  'datetimerange',
  'number',
  'dateampm'
];
const mixCalculator = {
  data() {
    return {
      init: 0,
      apiTime: null,
      reqTime: 200,
      erV: null,
      contentItems: []
    };
  },
  methods: {
    async apiCalInit(formData, formId) {
      return request.post(
        website.baseUrl  + '/api/form/calculate/init',
        formData,
        {
          params: {
            formId
          }
        }
      );
    },
    async apiCalRun(formData, params) {
      debugger
      return request.post(
        website.baseUrl  + '/api/form/calculate/run',
        formData,
        {
          params: {
            isRecursion: true,
            ...params
          }
        }
      );
    },
    async apiCalRunDynamic(formData, params) {
      return request.post(
          website.baseUrl+
          '/api/form/calculate/pop-up-submit',
        formData,
        {
          params
        }
      );
    },
    async apiCalRunDynamicAdd({ formData, subFormData }, params) {
      return request.post(
          website.baseUrl +
          '/api/form/calculate/pop-up-change',
        { formData, subFormData },
        {
          params
        }
      );
    },
    isReqTime() {
      if (this.apiTime) {
        const currentTime = new Date();
        const prevTiem = this.apiTime;
        prevTiem.setMilliseconds(prevTiem.getMilliseconds() + this.reqTime);
        if (currentTime.getTime() > prevTiem.getTime()) {
          return true;
        } else {
          return false;
        }
      } else {
        return true;
      }
    },
    setLabelPosition(column) {
      column.map((item) => {
        const { component, type, label } = item;
        const isTop = type === 'dynamic' || type === 'templateFile';
        if (isTop) {
          item.cplabel = label;
          item.label = '';
          item.labelPosition = 'top';
        }
      });
    },
    initDynamicStyle() {
      if (this.viewFormData?.option?.column.length) {
        this.setLabelPosition(this.viewFormData.option.column);
      }
      if (this.viewFormData?.option?.group?.length) {
        const groups = this.viewFormData.option.group;
        groups.map((item) => {
          this.setLabelPosition(item.column);
        });
      }
    },
    initDynamic() {
      if (this.viewFormData?.option?.column.length) {
        this.initDynamicByColumn(this.viewFormData.option.column);
      }
      if (this.viewFormData?.option?.group?.length) {
        const groups = this.viewFormData.option.group;
        groups.map((item) => {
          this.initDynamicByColumn(item.column);
        });
      }
    },
    initDynamicByColumn(optionColumn) {
      const dynamicCols = _.filter(optionColumn, { type: 'dynamic' });
      dynamicCols.map((dyncol) => {
        if (dyncol?.children?.column?.length) {
          const childrenCols = dyncol.children.column;
          dyncol.children.rowAdd = (done) => {
            done();
            this.init = 0;
            setTimeout(() => {
              this.init = 1;
            }, 2000);
          };
          childrenCols.map((itemChild) => {

            if (this.contentIncludes(`${dyncol.prop}.${itemChild.prop}`)) {
              itemChild.change = async ({ value, column }) => {

                if (this.init) {
                  const dyncolprop = dyncol.prop;
                  const columnprop = column.prop;
                  const currentDyn = this.viewFormData.form[dyncolprop];
                  let lineNum = null;
                  let num = 0;
                  let index = null;
                  currentDyn.map((item) => {
                    if (item[columnprop] === value) {
                      index = item.$index;
                      num += 1;
                    }
                  });
                  if (num === 1) {
                    lineNum = index;
                  }
                  if (index !== null) {
                    if (this.erV) {
                      this.erV = null;
                      return false;
                    } else {
                      this.erV = value;
                    }
                    await this.runFormData(`${dyncolprop}.${columnprop}`, {
                      lineNum
                    });
                  }
                }
              };
            }
          });
        }
      });
    },
    push2Items(item) {
      if (item.formulaType === 'number') {
        item.values.map((str) => {
          this.contentItems.push(str.trim());
        });
      } else {
        const { firstDateProp, secondDateProp } = item;
        this.contentItems.push(firstDateProp);
        this.contentItems.push(secondDateProp);
      }
    },
    isCalculated() {
      let flag = this.isCalculatedByColumn(this.viewFormData.option.column);
      if (this.viewFormData.option.group) {
        for (var i = 0; i < this.viewFormData.option.group.length; i++) {
          let groupItem = this.viewFormData.option.group[i];
          let tempFlag = this.isCalculatedByColumn(groupItem.column);
          if (tempFlag) {
            flag = tempFlag;
          }
        }
      }
      return flag;
    },
    isCalculatedByColumn(optionColumn) {
      const column = optionColumn.filter((item) => {
        const isRight = item.type === 'calculator';
        if (isRight) {
          this.push2Items(item);
        }
        return isRight;
      });
      const dynamicCols = optionColumn.filter(
        (item) => item.type === 'dynamic'
      );
      if (dynamicCols.length) {
        let isTrue = false;
        dynamicCols.map((dyncol) => {
          if (dyncol?.children?.column?.length) {
            const childrenCols = dyncol.children.column.filter((item) => {
              const isRight = item.type === 'calculator';
              if (isRight) {
                this.push2Items(item);
              }
              return isRight;
            });
            if (childrenCols.length) {
              isTrue = true;
            }
          }
        });
        if (isTrue) {
          return true;
        }
      }
      if (column.length) {
        return true;
      }
      return false;
    },
    // 判断是否触发计算
    contentIncludes(prop) {
      let is = false;
      let contentItems = this.contentItems;
      if (this.parentContentItems) {
        contentItems = this.parentContentItems;
      }
      for (let i = 0; i < contentItems.length; i++) {
        if (contentItems[i] === prop) {
          is = true;
          break;
        }
      }
      return is;
    },
    async initData() {

      if (this.viewFormData.pageKey &&  this.viewFormData.pageKey !== 'DO') {
        return false;
      }
      const { option, form } = this.viewFormData;

      // const column = this.viewFormData.option.column
      let column = [];
      this.viewFormData?.option?.column.forEach((itemColumn) => {
        column.push(itemColumn);
      });
      if (this.viewFormData?.option?.group?.length) {
        const groups = this.viewFormData.option.group;
        groups.map((item) => {
          item.column.forEach((itemColumn) => {
            column.push(itemColumn);
          });
        });
      }
      column.map((item) => {
        const { prop } = item;
        if (this.contentIncludes(prop)) {
          if (item.blur instanceof Function) {
            const oldfn = item.blur;
            item.blur = debounce(({ value, column }) => {
              this.runFormData(column.prop, { value });
              oldfn({ value, column });
            }, 500);
          } else {
            item.blur = debounce(({ column, value }) => {
              this.runFormData(column.prop, { value });
            }, 500);
          }
        }
      });

      // try {
      //   const { data } = await this.apiCalInit(form, formId);
      //
      //   const success =data.success || false;
      //   if(!success){
      //     this.$message.error(data.message);
      //     return
      //   }
      //   this.setModelData(data.data.data);
      // } catch ({ msg }) {
      //
      //   this.$message.error(msg);
      // }
    },
    async runFormData(changeField,value) {

      const { option, form,formId } = this.viewFormData;
      const params = {
        changeField,
        formId: formId
      };

      if (value) {
        form[changeField] = value.value?value.value:value;
      }

      // 同时传lineNum=0，1，2会导致计算结果同步问题
      // if (lineNum !== null) {
      //   params.lineNum = lineNum
      // }

      if (!this.isReqTime()) {
        return false;
      }

      // debounce(async () => {
      try {

        const { data } = await this.apiCalRun(form, params);
        const success =data.success || false;
        if(!success){
          this.$message.error(data.message);
          return
        }
        this.setModelData(data.data.data);
        this.apiTime = new Date();
      } catch ({ msg }) {

        this.$message.error(msg);
      }
      // }, 200);
    },
    setModelData(data) {

      for (const k in data) {
        const val = data[k];
        if (Array.isArray(val)) {
          // 直接修改原数组元素，避免不必要的对象解构和数组拷贝
          for (let i = 0; i < val.length; i++) {
            // 合并当前索引的modelData对象和data中的值
            for (const key in val[i]) {
              if (!this.viewFormData.form[k][i].hasOwnProperty(key)) {
                this.viewFormData.form[k][i][key] = val[i][key]
                // this.$set(this.viewFormData.form[k][i], key, val[i][key]);
              } else {
                this.viewFormData.form[k][i][key] = val[i][key];
              }
            }
          }
        } else {
          this.viewFormData.form[k] = val;

          //this.$set(this.viewFormData.form, k, val);
        }
      }
    },
    async runFormData2(propStr) {
      const { option, form,formId } = this.viewFormData;
      const params = {
        formId: formId,
        subProp: propStr
      };
      try {
        const { data } = await this.apiCalRunDynamic(form, params);

        const success =data.success || false;
        if(!success){
          this.$message.error(data.message);
          return
        }
        this.setModelData(data.data.data);
        // setTimeout(() => {
        //   this.setModelData(data);
        // },500)
      } catch ({ msg }) {

        this.$message.error(msg);
      }
    },
    async runFormAdd(fieldProp, subProp, subFormData) {
      const { option, form ,formId} = this.viewFormData;

      const params = {
        formId: formId,
        subProp,
        fieldProp
      };
      try {
        const { data } = await this.apiCalRunDynamicAdd({formData: form, subFormData},
          params
        );
        this.apiTime = new Date();
        return data.data.data;
      } catch ({ msg }) {

        this.$message.error(msg);
      }
      return null;
    },
    isDynamicProp(prop) {
      let str = '';
      let index = null;
      const dynamicCols = _.filter(this.viewFormData?.option?.column, {
        type: 'dynamic'
      });

      if (dynamicCols.length) {
        dynamicCols.map((dyncol) => {
          if (dyncol?.children?.column?.length) {
            const childrenCols = dyncol.children.column;
            for (let i = 0; i < childrenCols.length; i++) {
              const childCol = childrenCols[i];
              if (childCol.prop === prop) {
                // str = `${dyncol.prop}.${prop}`
                str = dyncol.prop;
                index = i;
                break;
              }
            }
          }
        });
      }
      return {
        str,
        index
      };
    }
  }
};

export default mixCalculator;
